package cn.shop.cloud.resolver;

import cn.shop.cloud.domain.User;
import cn.shop.cloud.redis.MemberServerKeyPrefix;
import cn.shop.cloud.redis.MyRedisTemplate;
import cn.shop.cloud.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: shop-parent
 * @ClassName UserMethodArgumentResolver
 * @description:
 * @author: Mokio
 * @create: 2024−12-24 21:25
 * @Version 2024 2.2 ; jdk1.8.0_181
 **/
//  < bean  id ="userMethodArgumentResolver"  class=""/>
public class UserMethodArgumentResolver  implements HandlerMethodArgumentResolver {

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //  public Result<User> getCurrent(@RedisValue User user)
        return methodParameter.getParameterType()== User.class &&
                // methodParameter.getMethodAnnotation(RedisValue.class)!=null;   //获取的是方法上面的注解
                methodParameter.getParameterAnnotation(RedisValue.class)!=null; //获取的是参数的注解
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        System.out.println("。。。。。。。。。。。。。。自定义参数解析器。。。。。。。。。。。。。。");
        //得到request对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        String token = CookieUtil.getCookie(request,CookieUtil.TOKEN_COOKIE_NAME);

        if(StringUtils.isEmpty(token)){
            return null;//没有token
        }
        //去Redis中拿到数据
        return myRedisTemplate.get(MemberServerKeyPrefix.USER_TOKEN,token,User.class);
    }
}
